package com.sen.config;


import com.sen.service.MyUserService;
import com.sen.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
//确保每一次请求都会被过滤并且只过滤一次
public class JwtAuthorizationTokenFilter extends OncePerRequestFilter {

    @Resource
    private MyUserService userDetailService;

    @Resource
    private JwtTokenUtil jwtTokenUtil;



    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
            //        获取请求中的token，第一次登陆token:空
            String token = request.getHeader(jwtTokenUtil.getHeader());
            log.info("token:" + token);
//        如果token不为空
        if (token != null && "".equals(token)) {
//            从token中获取用户名
            String username = jwtTokenUtil.getUsernameFromToken(token);
//            如果用户名不为空
//            SecurityContextHolder.getContext()：SpringSecurity中的上下文对象：全局对象，存认证信息
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
//                调用userDetailService ，获取数据库中存储的用户详情：用户名，权限列表。。。
                UserDetails userDetails = userDetailService.loadUserByUsername(username);
//                验证
                if (jwtTokenUtil.validateToken(token, userDetails)) {
//                    生成一个服务器端需要存储的令牌信息
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
//                    将令牌信息存入全局对象中
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }

        }
//        正常登录时：不需要验证token
            chain.doFilter(request, response);

    }
}
